import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);

//引入路由模块信息
import routes from './routes'
//引入仓库
import store from '@/store'
//重写push和replace方法，防止多次点击报错提示恶心人
let originPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        originPush.call(this, location, resolve, reject)
    } else {
        originPush.call(this, location, () => { }, () => { })
    }
}
let originReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function (location, resolve, reject) {
    if (resolve && reject) {
        originReplace.call(this, location, resolve, reject)
    } else {
        originReplace.call(this, location, () => { }, () => { })
    }
}

const router = new VueRouter({
    routes,
    scrollBehavior(to, from, savedPosition) {
        return {
            y: 0,
        }
    },
})
//全局前置路由守卫
router.beforeEach(async function (to, from, next) {
    //登陆了
    if (store.state.user.token) {
        //登陆了还要再登陆注册，不允许
        if (to.path == '/login'||to.path == '/register') {
            next('/home');
        } else {
            //没有用户信息获取用户信息
            if (!store.state.user.userInfo.name) {
                try {
                    //获取用户信息
                    await store.dispatch('user/getUserInfo');
                    next();
                } catch (error) {//token失效
                    //清除TOKEN
                    localStorage.removeItem('TOKEN');
                    store.state.user.token='';
                    // store.state.user.userInfo={};
                    // store.state.user.code='';
                    alert(error.message);
                    next('/login');
                }
            }else{
                next();
            }
        }
    } else {//没有登陆
        let path=to.path;
        if (path == '/pay' || path == '/paysuccess' || path == '/trade'||path.indexOf('/center')!=-1) {
            next('/login?redirect='+path);
        } else {//其他不允许
            next()
        }
        
    }
})

export default router
